package controller

import (
	"baliance.com/gooxml/document"
	"bufio"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/xuri/excelize/v2"
	"golang.org/x/text/encoding/simplifiedchinese"
	"golang.org/x/text/transform"
	"gorm.io/gorm"
	"gorm.io/gorm/clause"
	"mime/multipart"
	"mygo/app/models"
	"mygo/app/tools"
	"os"
	"strconv"
	"strings"
	"sync"
	"time"
)

type forecastCtl struct {
	fileNames []string
	tideNames []string
	db        *gorm.DB
}

var Forecast = forecastCtl{
	fileNames: []string{"浅滩高低潮.txt", "露滩时间.txt"},
	tideNames: []string{"YULIAO", "AOJIANG", "DONGTOU", "LONGWAN", "RUIAN", "SGTOU", "SHIPENG", "WENZHOU", "DAMEND", "NANJI"},
}

//var offsetMap = map[string]float64{
//	"玉寮":  -164,
//	"鳌江":  -186,
//	"洞头":  -333,
//	"龙湾":  -184,
//	"瑞安":  -186,
//	"沙港头": -100,
//	"石砰":  -182,
//	"温州":  -180,
//	"大门":  -0,
//	"南麂":  -0,
//	"北麂":  -0,
//}

// 定义一个锁
var mm sync.Mutex

func (ctl *forecastCtl) UploadFile(c *gin.Context) {
	ctl.db = models.Db
	//	接收文件,存到./public/txt
	file, err := c.FormFile("file")
	if strings.Contains(file.Filename, "天文潮") {
		//如果不是docx
		if !strings.Contains(file.Filename, "docx") {
			c.JSON(200, gin.H{
				"code":    500,
				"message": "请上传docx文件",
			})
			return
		}
		//mm.Lock()
		handelTwc(c, file, ctl.db)
		//mm.Unlock()
		return
	}
	if strings.Contains(file.Filename, "逐时") {
		handelZhushi(c, file, ctl.db)
		return
	}
	if strings.Contains(file.Filename, "霞关波浪报表") {
		//三澳每个小时海浪
		handelCondition(c, file, ctl.db)
		return
	}

	//cnhd2_120.633E_27.200N_20231219.txt
	if strings.Contains(file.Filename, "cnhd2") {
		//三澳每个小时海浪
		handelSaForeOne(c, file, ctl.db)
		return
	}
	if strings.Contains(file.Filename, "njd") {
		//三澳每个小时海浪
		handelRaForeOne(c, file, ctl.db)
		return
	}
	if strings.Contains(file.Filename, "波周期") {
		//三澳每个小时海浪
		handelSaForeXlsx(c, file, ctl.db)
		return
	}
	if strings.Contains(file.Filename, "fish") {
		//渔业每个小时海浪
		handelYyForeXlsx(c, file, ctl.db)
		return
	}
	if strings.Contains(file.Filename, "南麂列岛") || strings.Contains(file.Filename, "洞头列岛") {
		//渔业每个小时海浪
		handelHdrcForeTxt(c, file, ctl.db)
		return
	}
	if strings.Contains(file.Filename, "xhl") {
		//西航路文件上传
		handelXhlForeTxt(c, file, ctl.db)
		return
	}
	for _, v := range ctl.tideNames {
		if strings.Contains(file.Filename, v) {
			//之后都是这个无后缀文件来代替之前的一年天文潮
			handelTideNew(c, file, ctl.db)
			return
		}
	}
	//if strings.Contains(file.Filename, "cnhd2") {
	//	//三澳每个小时海浪
	//	handelSaForeOne(c, file, ctl.db)
	//	return
	//}
	//如果文件名不在fileNames中,则返回错误
	isFile := true
	for _, v := range ctl.fileNames {
		if strings.Contains(file.Filename, v) {
			isFile = false
			break
		}
	}
	if isFile {
		c.JSON(200, gin.H{
			"code":    500,
			"message": "上传错误文件",
		})
		return
	}
	if err != nil {
		c.JSON(200, gin.H{
			"code":    500,
			"message": "error",
		})
		return
	}
	//以gbk编码存储文件
	err = c.SaveUploadedFile(file, "./public/txt/"+file.Filename)
	if err != nil {
		c.JSON(200, gin.H{
			"code":    500,
			"message": "error",
		})
		return
	}

	fl, _ := os.Open("./public/txt/" + file.Filename)
	defer fl.Close()

	//	读取文件内容
	reader := transform.NewReader(bufio.NewReader(fl), simplifiedchinese.GBK.NewDecoder())

	// 使用bufio.NewScanner读取文件
	scanner := bufio.NewScanner(reader)
	//	存储文件内容
	//2023年6月2.0m露滩时间，，获取这种格式的日期
	year := strings.Split(file.Filename, "年")[0] + "年"
	month := strings.Split(strings.Split(file.Filename, "年")[1], "月")[0] + "月"
	//像6月这种改成06月
	if len(month) == 4 {
		month = "0" + month
	}
	if strings.Contains(file.Filename, "2.0m") {
		currentTime := ""
		for scanner.Scan() {
			var liangmi models.Liangmi
			value := strings.ReplaceAll(scanner.Text(), " ", "")
			//fmt.Println(value)
			if value == "" {
				continue
			} else {
				if strings.Contains(value, "日") {
					day := strings.Split(value, "日")[0] + "日"
					if len(day) == 4 {
						day = "0" + day
					}
					liangmi.Date = year + month + day
					currentTime = year + month + day
					//fmt.Println(liangmi.Date)
					if strings.Contains(value, "-") {
						finalValue := strings.Split(value, "日")[1]
						finalValue = strings.Replace(finalValue, "，", "", 1)
						liangmi.Data = finalValue
						//冲突合并
						ctl.db.Clauses(clause.OnConflict{
							Columns:   []clause.Column{{Name: "date"}},
							DoUpdates: clause.AssignmentColumns([]string{"data"}),
						}).Create(&liangmi)
					}
				} else {
					liangmi.Data = value
					liangmi.Date = currentTime
					//liangmi.Id = tools.GetUuid()
					//f.db.Create(&liangmi)
					//	如果存在日期相同则更新,不存在则创建
					//if f.db.Where("date = ?", liangmi.Date).First(&models.Liangmi{}).RowsAffected > 0 {
					//	f.db.Model(&models.Liangmi{}).Where("date = ?", liangmi.Date).Update("data", liangmi.Data)
					//} else {
					//	f.db.Create(&liangmi)
					//}

					ctl.db.Clauses(clause.OnConflict{
						Columns:   []clause.Column{{Name: "date"}},
						DoUpdates: clause.AssignmentColumns([]string{"data"}),
					}).Create(&liangmi)
				}
			}
		}
	} else if strings.Contains(file.Filename, "2.8m") {
		currentTime := ""
		for scanner.Scan() {
			var liangmi8 models.Liangmi8
			value := strings.ReplaceAll(scanner.Text(), " ", "")
			if value == "" {
				continue
			} else {
				if strings.Contains(value, "日") {
					//liangmi.Date = year + month + strings.Split(value, "日")[0] + "日"
					day := strings.Split(value, "日")[0] + "日"
					if len(day) == 4 {
						day = "0" + day
					}
					liangmi8.Date = year + month + day
					currentTime = year + month + day
					if strings.Contains(value, "-") {
						finalValue := strings.Split(value, "日")[1]
						finalValue = strings.Replace(finalValue, "，", "", 1)
						liangmi8.Data = finalValue
						//liangmi8.Id = tools.GetUuid()
						//f.db.Create(&liangmi)
						////	如果存在日期相同则更新,不存在则创建
						//if f.db.Where("date = ?", liangmi8.Date).First(&models.Liangmi8{}).RowsAffected > 0 {
						//	f.db.Model(&models.Liangmi8{}).Where("date = ?", liangmi8.Date).Update("data", liangmi8.Data)
						//} else {
						//	f.db.Create(&liangmi8)
						//}
						ctl.db.Clauses(clause.OnConflict{
							Columns:   []clause.Column{{Name: "date"}},
							DoUpdates: clause.AssignmentColumns([]string{"data"}),
						}).Create(&liangmi8)
					}
				} else {
					liangmi8.Data = value
					liangmi8.Date = currentTime
					//liangmi8.Id = tools.GetUuid()
					//f.db.Create(&liangmi)
					//	如果存在日期相同则更新,不存在则创建
					//if f.db.Where("date = ?", liangmi8.Date).First(&models.Liangmi8{}).RowsAffected > 0 {
					//	f.db.Model(&models.Liangmi8{}).Where("date = ?", liangmi8.Date).Update("data", liangmi8.Data)
					//} else {
					//	f.db.Create(&liangmi8)
					//}
					ctl.db.Clauses(clause.OnConflict{
						Columns:   []clause.Column{{Name: "date"}},
						DoUpdates: clause.AssignmentColumns([]string{"data"}),
					}).Create(&liangmi8)
				}
			}
		}
	} else {
		var tideList []models.TwcTide
		for scanner.Scan() {
			value := strings.ReplaceAll(scanner.Text(), " ", "")
			if value == "" || strings.Contains(value, "日期") {
				continue
			} else {
				valueArr := strings.Split(value, ",")
				for i, v := range valueArr {
					if (i+1)%2 == 0 && len(v) > 0 {
						valueArr[i] = v[0:2] + ":" + v[2:4]
					}
				}
				var tide models.TwcTide
				tide.Date = valueArr[0][0:4] + "-" + valueArr[0][4:6] + "-" + valueArr[0][6:8]
				tide.Station = "浅滩"
				tide.TimeHigh1 = valueArr[1]
				tide.TideHigh1 = valueArr[2]
				tide.TimeHigh2 = valueArr[3]
				tide.TideHigh2 = valueArr[4]
				tide.TimeLow1 = valueArr[5]
				tide.TideLow1 = valueArr[6]
				tide.TimeLow2 = valueArr[7]
				tide.TideLow2 = valueArr[8]
				tideList = append(tideList, tide)
			}
		}
		mm.Lock()
		ctl.db.Clauses(clause.OnConflict{
			Columns:   []clause.Column{{Name: "idx_date_station"}},
			DoUpdates: clause.AssignmentColumns([]string{"timeHigh1", "tideHigh1", "timeHigh2", "tideHigh2", "timeLow1", "tideLow1", "timeLow2", "tideLow2"}),
		}).Create(&tideList)
		mm.Unlock()
	}

	//打印文件名
	//fmt.Println(file.Filename)
	//获取当天的日期 YYYY-MM-DD
	date := time.Now().Format("2006-01-02")
	var fileList models.FileList
	fileList.FileName = file.Filename
	fileList.CreateTime = date
	fileList.State = "上传成功"
	ctl.db.Create(&fileList)
	c.JSON(200, gin.H{
		"code":    200,
		"message": "success",
		"result":  nil,
	})
}

// getFileList
func (ctl *forecastCtl) GetFileList(c *gin.Context) {
	ctl.db = models.Db
	var fileList []models.FileList
	t := c.Query("time")
	ctl.db.Where("createTime = ?", t).Find(&fileList)
	//c.JSON(200, gin.H{
	//	"code":    200,
	//	"message": "success",
	//	"result":  fileList,
	//})

	if len(fileList) > 0 {
		c.JSON(200, gin.H{
			"code":    200,
			"message": "success",
			"result":  fileList,
		})
	} else {
		c.JSON(200, gin.H{
			"code":    200,
			"message": "success",
			"result":  nil,
		})
	}
}

func handelTwc(c *gin.Context, file *multipart.FileHeader, db *gorm.DB) {
	fileName := "./public/word/" + file.Filename
	fileNameArr := strings.Split(file.Filename, "20")
	// 上传文件到指定的路径
	c.SaveUploadedFile(file, fileName)

	doc, _ := document.Open(fileName)
	var year, month string
	var twcList []models.TwcTide
	var twcHourList []models.TideHour
	for _, p := range doc.Paragraphs() {
		strRow := ""
		for i := 0; i < len(p.Runs()); i++ {
			strRow += p.Runs()[i].Text()
		}
		if len(p.Runs()) > 0 {
			//fmt.Println(len(strRow))
			strArr := strings.Split(strRow, "    ")
			if len(strArr) < 10 {
				tideStr := strRow[109:]
				tideHourStr := strRow[9:109]
				fmt.Println(tideHourStr[0:3])
				//tideStr长度不够39则补空格
				for len(tideStr) < 39 {
					tideStr += " "
				}
				day := strings.Replace(strArr[0], " ", "", -1)
				if len(day) == 1 {
					day = "0" + day
				}
				var valueArr []string
				valueArr = strings.Split(strArr[2], " ")
				var value []string
				for _, v := range valueArr {
					//	去除空格并且去除字符串中得空格
					if v != "" {
						value = append(value, strings.Replace(v, " ", "", -1))
					}
				}
				//长度不到4则补空字符串
				for len(value) < 8 {
					for i := 0; i < 8-len(value); i++ {
						value = append(value, "")
					}
				}
				for i, v := range value {
					vInt := len(v)
					if i%2 == 0 && vInt > 0 {
						value[i] = v[0:2] + ":" + v[2:4]
					}
				}
				var tideArr []string
				for _, v := range [][]int{{0, 4}, {4, 9}, {9, 14}, {14, 19}, {19, 24}, {24, 29}, {29, 34}, {34, 39}} {
					tideArr = append(tideArr, tools.TrimSpace(tideStr[v[0]:v[1]]))
				}
				for i, v := range tideArr {
					vInt := len(v)
					if i%2 == 0 && vInt > 0 {
						tideArr[i] = v[0:2] + ":" + v[2:4]
					}
				}

				for idx, v := range [][]int{{0, 3}, {4, 7}, {8, 11}, {12, 15}, {16, 19}, {20, 23}, {24, 27}, {28, 31}, {32, 35}, {36, 39}, {40, 43}, {44, 47}, {48, 51}, {52, 55}, {56, 59}, {60, 63}, {64, 67}, {68, 71}, {72, 75}, {76, 79}, {80, 83}, {84, 87}, {88, 91}, {92, 95}} {
					tideHourItem := tools.TrimSpace(tideHourStr[v[0]:v[1]])
					if len(tideHourItem) == 0 {
						tideHourItem = "0.00"
					}
					t := ""
					if idx < 10 {
						t = "0" + strconv.Itoa(idx) + ":00"
					} else {
						t = strconv.Itoa(idx) + ":00"
					}
					var tideHour models.TideHour
					tideHour.Date = year + "-" + month + "-" + day
					tideHour.Time = t
					tideHour.Tide = tools.Float64ToFixedStr(tools.StrToFloat64(tideHourItem)/100-1.64, 2)
					tideHour.Station = "北麂"
					twcHourList = append(twcHourList, tideHour)
				}

				var twcTide = models.TwcTide{
					Date:    year + "-" + month + "-" + day,
					Station: fileNameArr[0],
					//TimeHigh1: value[0],
					//TideHigh1: value[1],
					//TimeHigh2: value[2],
					//TideHigh2: value[3],
					//TimeLow1:  value[4],
					//TideLow1:  value[5],
					//TimeLow2:  value[6],
					//TideLow2:  value[7],
					TimeHigh1: tideArr[0],
					TideHigh1: tideArr[1],
					TimeHigh2: tideArr[2],
					TideHigh2: tideArr[3],
					TimeLow1:  tideArr[4],
					TideLow1:  tideArr[5],
					TimeLow2:  tideArr[6],
					TideLow2:  tideArr[7],
				}
				//	查找是否存在date相同的，存在则更新，不存在则创建
				//if db.Where("date = ? AND station = ?", twcTide.Date, fileNameArr[0]).First(&models.TwcTide{}).RowsAffected > 0 {
				//	db.Model(&models.TwcTide{}).Where("date = ? AND station = ?", twcTide.Date, fileNameArr[0]).Updates(&twcTide)
				//} else {
				//	db.Create(&twcTide)
				//}
				twcList = append(twcList, twcTide)
				//if len(twcList) == 100 {
				//	models.Db.Clauses(clause.OnConflict{
				//		Columns:   []clause.Column{{Name: "idx_date_station"}},
				//		DoUpdates: clause.AssignmentColumns([]string{"timeHigh1", "tideHigh1", "timeHigh2", "tideHigh2"}),
				//	}).Create(&twcList)
				//	twcList = nil
				//}
			} else {
				str := strings.ReplaceAll(p.Runs()[0].Text(), " ", "")
				if strings.Contains(str, "20") { //2023年的那个20
					var arr []string
					for _, v := range strArr {
						if v != "" {
							arr = append(arr, v)
						}
					}
					year = strings.Replace(arr[0], " ", "", -1)
					month = strings.Replace(arr[1], " ", "", -1)
					//	补0
					if len(month) == 1 {
						month = "0" + month
					}
				}

			}
		}
	}
	mm.Lock()
	models.Db.Clauses(clause.OnConflict{
		Columns:   []clause.Column{{Name: "idx_date_station"}},
		DoUpdates: clause.AssignmentColumns([]string{"timeHigh1", "tideHigh1", "timeHigh2", "tideHigh2", "timeLow1", "tideLow1", "timeLow2", "tideLow2"}),
	}).Create(&twcList)
	mm.Unlock()

	mm.Lock()
	models.Db.Clauses(clause.OnConflict{
		Columns:   []clause.Column{{Name: "idx_date_time_station"}},
		DoUpdates: clause.AssignmentColumns([]string{"tide"}),
	}).Create(&twcHourList)
	mm.Unlock()
	date := time.Now().Format("2006-01-02")
	var fileList models.FileList
	fileList.FileName = file.Filename
	fileList.CreateTime = date
	fileList.State = "上传成功"
	db.Create(&fileList)
	c.JSON(200, gin.H{
		"code":    200,
		"message": "success111",
		"result":  nil,
	})
}

// handelZhushi
func handelZhushi(c *gin.Context, file *multipart.FileHeader, db *gorm.DB) {
	//	文件必须是txt格式
	if !strings.Contains(file.Filename, ".txt") {
		c.JSON(200, gin.H{
			"code":    500,
			"message": "上传错误文件",
		})
		return
	}
	//	按行读取文件
	fileName := "./public/word/" + file.Filename
	// 上传文件到指定的路径
	c.SaveUploadedFile(file, fileName)
	fl, _ := os.Open(fileName)
	defer fl.Close()
	//	读取文件内容
	reader := transform.NewReader(bufio.NewReader(fl), simplifiedchinese.GBK.NewDecoder())
	// 使用bufio.NewScanner读取文件
	scanner := bufio.NewScanner(reader)
	//	存储文件内容
	//	遍历
	var date string = ""
	var tideHourList []models.TideHour
	for scanner.Scan() {
		//fmt.Println(scanner.Text())
		valueArr := strings.Split(scanner.Text(), " ")
		//	去除空格
		var value []string
		for _, v := range valueArr {
			if v != "" {
				value = append(value, v)
			}
		}
		//	如果长度小于3则跳过
		if len(value) != 3 {
			continue
		}
		if value[0] != date {
			date = value[0]
		}
		var tideHour models.TideHour
		tideHour.Date = date
		tideHour.Time = value[1]
		tideHour.Tide = value[2]
		tideHour.Station = "浅滩"

		tideHourList = append(tideHourList, tideHour)

		//db.Clauses(clause.OnConflict{
		//	Columns:   []clause.Column{{Name: "idx_date_time_station"}},
		//	DoUpdates: clause.AssignmentColumns([]string{"tide"}),
		//}).Create(&tideHour)
		//	查找是否存在date和time都相同的，存在则更新，不存在则创建
		//if db.Where("date = ? and time = ?", tideHour.Date, tideHour.Time).First(&models.TideHour{}).RowsAffected > 0 {
		//	db.Model(&models.TideHour{}).Where("date = ? and time = ?", tideHour.Date, tideHour.Time).Update("tide", tideHour.Tide)
		//} else {
		//	db.Create(&tideHour)
		//}

	}
	mm.Lock()
	db.Clauses(clause.OnConflict{
		Columns:   []clause.Column{{Name: "idx_date_time_station"}},
		DoUpdates: clause.AssignmentColumns([]string{"tide"}),
	}).Create(&tideHourList)
	mm.Unlock()
	date1 := time.Now().Format("2006-01-02")
	var fileList models.FileList
	fileList.FileName = file.Filename
	fileList.CreateTime = date1
	fileList.State = "上传成功"
	db.Create(&fileList)
	c.JSON(200, gin.H{
		"code":    200,
		"message": "success",
		"result":  nil,
	})
}

// SavePng
func (ctl *forecastCtl) SavePng(c *gin.Context) {
	//	获取文件
	file, err := c.FormFile("file")
	if err != nil {
		c.JSON(200, gin.H{
			"code":    500,
			"message": "error",
		})
		return
	}
	//	获取文件名
	fileName := file.Filename
	//	获取文件后缀
	fileSuffix := fileName[strings.LastIndex(fileName, "."):]
	//	判断文件后缀是否为png
	if fileSuffix != ".png" {
		c.JSON(200, gin.H{
			"code":    500,
			"message": "上传错误文件",
		})
		return
	}
	//	保存文件
	err = c.SaveUploadedFile(file, "./public/png/"+file.Filename)
	//睡眠1秒
	if err != nil {
		c.JSON(200, gin.H{
			"code":    500,
			"message": "error",
		})
		return
	}

	c.JSON(200, gin.H{
		"code":    200,
		"message": "success",
		"result":  file.Filename,
	})
}

// deletePng
func (ctl *forecastCtl) DeletePng(c *gin.Context) {
	fileName := c.Query("fileName")
	err := os.Remove("./public/png/" + fileName)
	if err != nil {
		c.JSON(200, gin.H{
			"code":    500,
			"message": "error",
		})
		return
	}
	c.JSON(200, gin.H{
		"code":    200,
		"message": "success",
		"result":  nil,
	})
}

type XlsxData struct {
	//Key   string `json:"key"`
	//Value string `json:"value"`
	Sheet string `json:"sheet"`
	Data  []struct {
		Key   string `json:"key"`
		Value string `json:"value"`
	} `json:"data"`
}

// CreateForeXlsx
func (ctl *forecastCtl) CreateForeXlsx(c *gin.Context) {

	t := c.Query("type")
	outName := c.Query("fileName")
	var xlsxDataArr []XlsxData
	c.ShouldBind(&xlsxDataArr)

	fileName := ""
	if t == "fb" {
		fileName = "./public/预报单模板/fb.xlsx"
	} else {
		fileName = "./public/预报单模板/ydyl.xlsx"
	}
	f, err := excelize.OpenFile(fileName)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer func() {
		if err := f.Close(); err != nil {
			fmt.Println(err)
		}
	}()

	for _, v := range xlsxDataArr {
		for _, v1 := range v.Data {
			f.SetCellValue(v.Sheet, v1.Key, v1.Value)
		}
	}
	f.SaveAs("./public/ybd/" + outName + ".xlsx")
	c.JSON(200, gin.H{
		"code":    200,
		"message": "success",
		"result":  nil,
	})
}

// 上传新的格式（txt或者无后缀）潮位数据得读取入库handelSaForeOne
func handelSaForeOne(c *gin.Context, file *multipart.FileHeader, db *gorm.DB) {
	if !strings.Contains(file.Filename, ".txt") {
		c.JSON(200, gin.H{
			"code":    500,
			"message": "上传错误文件",
		})
		return
	}
	//	按行读取文件
	fileName := "./public/word/" + file.Filename
	// 上传文件到指定的路径
	c.SaveUploadedFile(file, fileName)
	fl, _ := os.Open(fileName)
	defer fl.Close()
	//	读取文件内容
	reader := transform.NewReader(bufio.NewReader(fl), simplifiedchinese.GBK.NewDecoder())
	// 使用bufio.NewScanner读取文件
	scanner := bufio.NewScanner(reader)
	var SaForeOneList []models.SaForeOne
	for scanner.Scan() {
		row := scanner.Text()
		if !strings.Contains(row, "20") {
			continue
		}
		rowArr := strings.Split(row, " ")
		//	去除空格
		var value []string
		for _, v := range rowArr {
			if v != "" {
				value = append(value, v)
			}
		}
		SaForeOneList = append(SaForeOneList, models.SaForeOne{
			Date:       value[0][0:4] + "-" + value[0][4:6] + "-" + value[0][6:8],
			Time:       value[0][8:10] + ":00",
			WaveValue:  value[1],
			WaveAngle:  value[2],
			SurgeValue: value[6],
			SurgeAngle: value[5],
		})
	}
	mm.Lock()
	db.Clauses(clause.OnConflict{
		Columns:   []clause.Column{{Name: "idx_date_time"}},
		DoUpdates: clause.AssignmentColumns([]string{"waveValue", "waveAngle", "surgeValue", "surgeAngle"}),
	}).Create(&SaForeOneList)
	mm.Unlock()
	c.JSON(200, gin.H{
		"code":    200,
		"message": "success",
		"result":  nil,
	})
}

// handelRaForeOne
func handelRaForeOne(c *gin.Context, file *multipart.FileHeader, db *gorm.DB) {
	if !strings.Contains(file.Filename, ".txt") {
		c.JSON(200, gin.H{
			"code":    500,
			"message": "上传错误文件",
		})
		return
	}
	//	按行读取文件
	fileName := "./public/word/" + file.Filename
	// 上传文件到指定的路径
	c.SaveUploadedFile(file, fileName)
	fl, _ := os.Open(fileName)
	defer fl.Close()
	//	读取文件内容
	reader := transform.NewReader(bufio.NewReader(fl), simplifiedchinese.GBK.NewDecoder())
	// 使用bufio.NewScanner读取文件
	scanner := bufio.NewScanner(reader)
	var raForeOneList []models.RaForeOne
	for scanner.Scan() {
		row := scanner.Text()
		if !strings.Contains(row, "20") {
			continue
		}
		rowArr := strings.Split(row, " ")
		//	去除空格
		var value []string
		for _, v := range rowArr {
			if v != "" {
				value = append(value, v)
			}
		}
		raForeOneList = append(raForeOneList, models.RaForeOne{
			Date:      value[0][0:4] + "-" + value[0][4:6] + "-" + value[0][6:8],
			Time:      value[0][8:10] + ":00",
			WaveValue: value[1],
			WaveAngle: value[2],
		})
	}
	mm.Lock()
	db.Clauses(clause.OnConflict{
		Columns:   []clause.Column{{Name: "idx_date_time"}},
		DoUpdates: clause.AssignmentColumns([]string{"waveValue", "waveAngle"}),
	}).Create(&raForeOneList)
	mm.Unlock()
	c.JSON(200, gin.H{
		"code":    200,
		"message": "success",
		"result":  nil,
	})
}

var stationMap = map[string]string{
	"YULIAO":  "玉寮",
	"AOJIANG": "鳌江",
	"DONGTOU": "洞头",
	"LONGWAN": "龙湾",
	"RUIAN":   "瑞安",
	"SGTOU":   "沙港头",
	"SHIPENG": "石砰",
	"WENZHOU": "温州",
	"DAMEND":  "大门",
	"NANJI":   "南麂",
}

//var offsetMap = map[string]float64{
//	"YULIAO":  -1.64,
//	"AOJIANG": -1.86,
//	"DONGTOU": -3.33,
//	"LONGWAN": -1.84,
//	"RUIAN":   -1.86,
//	"SGTOU":   -0,
//	"SHIPENG": -0,
//	"WENZHOU": -0,
//	"DAMEND":  -0,
//	"NANJI":   -0,
//}

// handelTideNew
func handelTideNew(c *gin.Context, file *multipart.FileHeader, db *gorm.DB) {
	//获取file.Filename最后四个字符
	year := file.Filename[len(file.Filename)-4:]
	//date从year的第一天开始
	date := year + "-01-01"
	//	按行读取文件
	fileName := "./public/word/" + file.Filename
	// 上传文件到指定的路径
	c.SaveUploadedFile(file, fileName)
	fl, _ := os.Open(fileName)
	defer fl.Close()
	//	读取文件内容
	reader := transform.NewReader(bufio.NewReader(fl), simplifiedchinese.GBK.NewDecoder())
	// 使用bufio.NewScanner读取文件
	scanner := bufio.NewScanner(reader)
	var tideList []models.TwcTide
	var tideHourList []models.TideHour
	for scanner.Scan() {
		row := scanner.Text()
		if !strings.Contains(row, "9") {
			continue
		}
		rowArr := strings.Split(row, " ")
		//	去除空格
		var value []string
		for _, v := range rowArr {
			if v != "" {
				value = append(value, v)
			}
		}
		for idx, v := range value {
			if v == "9999" {
				value[idx] = ""
				continue
			}
			if idx < 24 {
				hour := strconv.Itoa(idx)
				if len(hour) == 1 {
					hour = "0" + hour
				}
				tide := tools.Float64ToFixedStr(tools.StrToFloat64(v)/100-1.64, 2)
				if tide == "" {
					tide = "0.00"
				}
				tideHourList = append(tideHourList, models.TideHour{
					Date:    date,
					Time:    hour + ":00",
					Tide:    tide,
					Station: stationMap[strings.Split(file.Filename, "20")[0]],
				})
			}
			if idx == 24 || idx == 26 || idx == 30 || idx == 32 {
				//value[idx] = value[idx][0:2] + ":" + value[idx][2:4]
				if len(value[idx]) == 2 {
					value[idx] = "00:" + value[idx]
				} else if len(value[idx]) == 3 {
					value[idx] = "0" + value[idx][0:1] + ":" + value[idx][1:3]
				} else if len(value[idx]) == 4 {
					value[idx] = value[idx][0:2] + ":" + value[idx][2:4]
				} else if len(value[idx]) == 1 {
					value[idx] = "00:0" + value[idx]
				}
			}
			//if idx == 25 || idx == 27 || idx == 31 || idx == 33 {
			//	//	数值减少164
			//	value[idx] = tools.IntToStr(tools.StrToInt(value[idx]) - 164)
			//}
		}
		h1 := tools.StrToFloat64(value[25]) + offsetMap[stationMap[strings.Split(file.Filename, "20")[0]]]
		h2 := tools.StrToFloat64(value[27]) + offsetMap[stationMap[strings.Split(file.Filename, "20")[0]]]
		l1 := tools.StrToFloat64(value[31]) + offsetMap[stationMap[strings.Split(file.Filename, "20")[0]]]
		l2 := tools.StrToFloat64(value[33]) + offsetMap[stationMap[strings.Split(file.Filename, "20")[0]]]
		tideList = append(tideList, models.TwcTide{
			Date:      date,
			TimeHigh1: value[24],
			TideHigh1: tools.Float64ToFixedStr(h1, 0),
			TimeHigh2: value[26],
			TideHigh2: tools.Float64ToFixedStr(h2, 0),
			TimeLow1:  value[30],
			TideLow1:  tools.Float64ToFixedStr(l1, 0),
			TimeLow2:  value[32],
			TideLow2:  tools.Float64ToFixedStr(l2, 0),
			Station:   stationMap[strings.Split(file.Filename, "20")[0]],
		})
		//	日期加一天
		t, _ := time.Parse("2006-01-02", date)
		date = t.AddDate(0, 0, 1).Format("2006-01-02")
	}
	mm.Lock()
	db.Clauses(clause.OnConflict{
		Columns:   []clause.Column{{Name: "idx_date_station"}},
		DoUpdates: clause.AssignmentColumns([]string{"timeHigh1", "tideHigh1", "timeHigh2", "tideHigh2", "timeLow1", "tideLow1", "timeLow2", "tideLow2"}),
	}).Create(&tideList)
	mm.Unlock()
	mm.Lock()
	db.Clauses(clause.OnConflict{
		Columns:   []clause.Column{{Name: "idx_date_time_station"}},
		DoUpdates: clause.AssignmentColumns([]string{"tide"}),
	}).Create(&tideHourList)
	mm.Unlock()
	c.JSON(200, gin.H{
		"code":    200,
		"message": "success",
		"result":  nil,
	})
}

// handelSaForeXlsx
func handelSaForeXlsx(c *gin.Context, file *multipart.FileHeader, db *gorm.DB) {
	date := strings.Split(file.Filename, "_")[0]
	t, _ := time.Parse("2006-01-02", date)
	//格式化时间
	fileName := "./public/word/" + file.Filename
	c.SaveUploadedFile(file, fileName)
	f, err := excelize.OpenFile(fileName)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer f.Close()
	var saForeOneList []models.SaForeOne
	Arr := [][]string{{"A", "17"}, {"B", "19"}, {"C", "21"}, {"D", "23"}, {"E", "1"}, {"F", "3"}, {"G", "5"}, {"H", "7"}, {"I", "9"}, {"J", "11"}, {"K", "13"}, {"L", "15"}, {"M", "17"}}
	for _, v := range Arr {
		tStr := t.Format("2006-01-02")
		if v[1] == "23" {
			t = t.AddDate(0, 0, 1)
		}
		if tools.StrToInt(v[1]) < 10 {
			v[1] = "0" + v[1]
		}
		circle, _ := f.GetCellValue("Sheet1", v[0]+"1")
		windValue, _ := f.GetCellValue("Sheet1", v[0]+"2")
		windAngle, _ := f.GetCellValue("Sheet1", v[0]+"3")
		saForeOneList = append(saForeOneList, models.SaForeOne{
			Date:      tStr,
			Time:      v[1] + ":00",
			Cycle:     circle,
			WindValue: windValue,
			WindAngle: windAngle,
		})
	}
	idx := 5
	var xhlDataArr []models.XhlData
	for {
		tt, _ := f.GetCellValue("Sheet1", "A"+tools.Float64ToStr(float64(idx)))
		w1, _ := f.GetCellValue("Sheet1", "B"+tools.Float64ToStr(float64(idx)))
		//wd1, _ := f.GetCellValue("Sheet1", "C"+tools.Float64ToStr(float64(idx)))
		w2, _ := f.GetCellValue("Sheet1", "D"+tools.Float64ToStr(float64(idx)))
		//wd2, _ := f.GetCellValue("Sheet1", "E"+tools.Float64ToStr(float64(idx)))
		w3, _ := f.GetCellValue("Sheet1", "F"+tools.Float64ToStr(float64(idx)))
		//wd3, _ := f.GetCellValue("Sheet1", "G"+tools.Float64ToStr(float64(idx)))

		if tt == "" {
			break
		}

		wind := tools.MaxFloat64([]float64{tools.StrToFloat64(w1), tools.StrToFloat64(w2), tools.StrToFloat64(w3)})
		var xhlData models.XhlData
		ttD := strings.Split(tt, " ")
		ttT := strings.Split(ttD[1], ":")
		xhlData.Date = ttD[0]
		xhlData.Time = ttT[0] + ":" + ttT[1]
		xhlData.WindValue = tools.Float64ToFixedStr(wind, 1)
		xhlData.WindAngle = "100"
		xhlData.WaveValue = "0.00"
		xhlData.WaveAngle = "100"
		xhlData.File = "sa"
		xhlDataArr = append(xhlDataArr, xhlData)
		idx++
		//fmt.Println(f.GetCellValue("Sheet1", "A"+tools.Float64ToStr(float64(idx))))
	}
	mm.Lock()
	db.Clauses(clause.OnConflict{
		Columns:   []clause.Column{{Name: "idx_date_time"}},
		DoUpdates: clause.AssignmentColumns([]string{"cycle", "windValue", "windAngle"}),
	}).Create(&saForeOneList)
	mm.Unlock()

	mm.Lock()
	db.Clauses(clause.OnConflict{
		Columns:   []clause.Column{{Name: "idx_date_time_file"}},
		DoUpdates: clause.AssignmentColumns([]string{"waveValue", "waveAngle", "windValue", "windAngle"}),
	}).Create(&xhlDataArr)

	mm.Unlock()
	c.JSON(200, gin.H{
		"code":    200,
		"message": "success",
		"result":  nil,
	})
}

func handelYyForeXlsx(c *gin.Context, file *multipart.FileHeader, db *gorm.DB) {
	fileName := "./public/word/" + file.Filename
	c.SaveUploadedFile(file, fileName)
	f, err := excelize.OpenFile(fileName)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer f.Close()
	num := 2
	for {
		value, _ := f.GetCellValue("Sheet1", "A"+tools.IntToStr(num))
		if value == "" {
			break
		}
		dateArr := strings.Split(value, " ")
		date := dateArr[0]
		time := strings.Split(dateArr[1], ":")[0] + ":00"
		//value1, _ := f.GetCellValue("Sheet1", "B"+tools.IntToStr(num))
		var valueArr []string
		for _, v := range []string{"B", "C", "D", "E", "F", "G"} {
			valueCell, _ := f.GetCellValue("Sheet1", v+tools.IntToStr(num))
			valueArr = append(valueArr, valueCell)
		}
		valueStr := strings.Join(valueArr, ",")
		var yyFore models.YyFore
		yyFore.Date = date
		yyFore.Time = time
		yyFore.WaveValue = valueStr
		mm.Lock()
		db.Clauses(clause.OnConflict{
			Columns:   []clause.Column{{Name: "idx_date_time"}},
			DoUpdates: clause.AssignmentColumns([]string{"waveValue"}),
		}).Create(&yyFore)
		mm.Unlock()
		num++
	}
	c.JSON(200, gin.H{
		"code":    200,
		"message": "success",
		"result":  nil,
	})
}

func handelHdrcForeTxt(c *gin.Context, file *multipart.FileHeader, db *gorm.DB) {
	//获取file.Filename最后四个字符
	//year := strings.Join(tools.GetNum(file.Filename), "")
	var year string
	for _, v := range tools.GetNum(file.Filename) {
		year += tools.IntToStr(v)
	}
	//date := year + "-01-01"
	//	按行读取文件
	fileName := "./public/word/" + file.Filename
	station := ""
	if strings.Contains(file.Filename, "南麂") {
		station = "南麂"
	} else if strings.Contains(file.Filename, "洞头") {
		station = "洞头"
	}
	// 上传文件到指定的路径
	c.SaveUploadedFile(file, fileName)
	fl, _ := os.Open(fileName)
	defer fl.Close()
	//	读取文件内容
	reader := transform.NewReader(bufio.NewReader(fl), simplifiedchinese.GBK.NewDecoder())
	scanner := bufio.NewScanner(reader)
	colArr := [12][2]int{{4, 13}, {15, 24}, {26, 35}, {37, 46}, {48, 57}, {59, 68}, {70, 79}, {81, 90}, {92, 101}, {103, 112}, {114, 123}, {125, 134}}
	for scanner.Scan() {
		rowLen := len(scanner.Text())
		for idx, v := range colArr {
			if rowLen < v[1] {
				continue
			}
			row := scanner.Text()[v[0]:v[1]]
			//去除前后的空格
			row = strings.TrimSpace(row)
			if row == "" {
				continue
			}
			month := tools.IntToStr(idx + 1)
			if len(month) == 1 {
				month = "0" + month
			}
			day := scanner.Text()[0:2]
			//如果day不是数字则跳过
			if !tools.IsNum(day) {
				continue
			}

			valueArr := strings.Split(row, " ")

			var hdrcFore models.Hdrc
			hdrcFore.Date = year + "-" + month + "-" + day
			hdrcFore.TimeRc = valueArr[0][0:2] + ":" + valueArr[0][2:4]
			hdrcFore.TimeRl = valueArr[1][0:2] + ":" + valueArr[1][2:4]
			hdrcFore.Station = station
			mm.Lock()
			db.Clauses(clause.OnConflict{
				Columns:   []clause.Column{{Name: "idx_date_station"}},
				DoUpdates: clause.AssignmentColumns([]string{"timeRc", "timeRl"}),
			}).Create(&hdrcFore)
			mm.Unlock()
		}
	}
	c.JSON(200, gin.H{
		"code":    200,
		"message": "success",
		"result":  nil,
	})
}

// handelCondition
func handelCondition(c *gin.Context, file *multipart.FileHeader, db *gorm.DB) {
	//	读取excel
	fileName := "./public/word/" + file.Filename
	c.SaveUploadedFile(file, fileName)
	f, err := excelize.OpenFile(fileName)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer f.Close()
	//	获取所有的sheet
	sheetList := f.GetSheetList()
	//	遍历sheet
	var conditionList []models.Condition
	for _, sheet := range sheetList {
		rows, _ := f.GetRows(sheet)
		if len(rows) < 20 {
			continue
		}
		//遍历
		for _, v := range rows {
			if len(v) > 20 && strings.Contains(v[0], "MF") {
				var condition models.Condition
				t := strings.Split(v[2], " ")
				condition.Station = v[0]
				condition.Date = t[0]
				condition.Time = t[1]
				condition.WindSpeedAvg = v[12]
				condition.WindAngleAvg = v[13]
				condition.WindSpeedMax = v[14]
				condition.WindAngleMax = v[15]
				condition.WaveHeightMax = v[29]
				condition.WavePeriodMax = v[30]
				condition.WaveHeightYx = v[31]
				condition.WavePeriodYx = v[32]
				conditionList = append(conditionList, condition)
			}
		}
	}
	mm.Lock()
	db.Clauses(clause.OnConflict{
		Columns:   []clause.Column{{Name: "idx_date_time_station"}},
		DoUpdates: clause.AssignmentColumns([]string{"windSpeedAvg", "windAngleAvg", "windSpeedMax", "windAngleMax", "waveHeightMax", "wavePeriodMax", "waveHeightYx", "wavePeriodYx"}),
	}).Create(&conditionList)
	mm.Unlock()

	c.JSON(200, gin.H{
		"code":    200,
		"message": "success",
		"result":  nil,
	})
}

// handelXhlForeTxt
func handelXhlForeTxt(c *gin.Context, file *multipart.FileHeader, db *gorm.DB) {
	fileName := "./public/word/" + file.Filename
	fileHeader := strings.Split(file.Filename, "_")[0]
	// 上传文件到指定的路径
	c.SaveUploadedFile(file, fileName)
	fl, _ := os.Open(fileName)
	defer fl.Close()
	//	读取文件内容
	reader := transform.NewReader(bufio.NewReader(fl), simplifiedchinese.GBK.NewDecoder())
	scanner := bufio.NewScanner(reader)
	//	逐行打印
	var xhlData []models.XhlData
	fmt.Println(fileHeader)
	for scanner.Scan() {
		row := scanner.Text()
		//根据“ ”分割，再去掉数组中的空字符串

		rowArr := strings.Split(row, " ")
		//	去除空格
		var value []string
		for _, v := range rowArr {
			if v != "" {
				value = append(value, v)
			}
		}

		if value[0] == "time" {
			continue
		}

		var xhl models.XhlData

		xhl.Date = value[0][0:4] + "-" + value[0][4:6] + "-" + value[0][6:8]
		xhl.Time = value[0][8:10] + ":00"
		xhl.File = fileHeader
		xhl.WaveValue = value[1]
		xhl.WaveAngle = value[2]
		xhl.WindValue = value[11]
		xhl.WindAngle = value[12]

		xhlData = append(xhlData, xhl)
	}

	mm.Lock()
	db.Clauses(clause.OnConflict{
		Columns:   []clause.Column{{Name: "idx_date_time_file"}},
		DoUpdates: clause.AssignmentColumns([]string{"waveValue", "waveAngle", "windValue", "windAngle"}),
	}).Create(&xhlData)

	mm.Unlock()
	c.JSON(200, gin.H{
		"code":    200,
		"message": "success",
		"result":  nil,
	})
}
